<template>
  <view class="container">

    <!-- 搜索框容器 -->
     <view class="search-wrapper">
       <!-- 输入框 -->
       <input 
         type="text" 
         v-model="searchValue" 
         placeholder="搜索您想要的" 
         class="search-input"
         @confirm="handleSearch" 
       />
       
       <!-- 放大镜图标（同时作为搜索按钮） -->
       <view class="search-icon" @click="handleSearch">
         <uni-icons type="search" size="20" color="#999"></uni-icons>
       </view>
     </view>

    <!-- 轮播图 -->
    <swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" @change="changeSwiper">
      <swiper-item v-for="(item, index) in bannerData" :key="index">
        <view class="swiper-item" @click="clickBannerItem(item)">
          <image :src="item.configValue" mode="aspectFill" :draggable="false" />
        </view>
      </swiper-item>
    </swiper>

    <!-- 新增广告位：轮播图下方，分类上方 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="ad-container">
      <ad 
        unit-id="你的广告位ID"  
        ad-type="banner"
        :ad-intervals="30"
        @load="onAdLoad"
        @error="onAdError"
        class="banner-ad"
      ></ad>
    </view>
    <!-- #endif -->

    <!-- 滚动通知栏 (自动滚动) -->
    <view class="notice-bar-container">
      <uni-icons type="sound-filled" size="18" color="#FF0000" class="notice-icon"></uni-icons>
      <view class="notice-content">
        <text class="notice-text" :animation="animationData">{{ noticeText }}</text>
      </view>
    </view>

    <!-- 五行功能模块 -->
    <view class="function-modules-container">
      <view class="function-modules-card">
        <view 
          class="module-item" 
          v-for="(item, index) in modules" 
          :key="index" 
          @click="navigateToModule(item)"
        >
          <view class="module-icon-wrapper">
            <image :src="item.icon" mode="aspectFit" class="module-icon"></image>
          </view>
          <text class="module-title">{{ item.title }}</text>
        </view>
		<view 
		      class="module-item" 
		      @click="navigateToAllCategories"
		    >
		      <view class="module-icon-wrapper">
		        <!-- 使用SVG图标 -->
		        <svg class="module-icon" viewBox="0 0 24 24" width="40rpx" height="40rpx">
		          <path fill="#1890ff" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10-4.48-10-10-10zm0 18c-4.41 0-8-3.59-8-8v-2v-2h16v2v2h-8v2c0 2.22-1.78 4-4 4zm8-6v-4h-6v4h6v10h10v-2h-11v-8z"/>
		        </svg>
		      </view>
		      <text class="module-title">全部分类</text>
		    </view>
		
      </view>
    </view>

    <!-- 最近更新 (带图标和更多按钮) -->
    <view class="recent-updates">
      <view class="updates-header">
        <view class="header-left">
          <uni-icons type="notification-filled" size="20" color="#1890ff"></uni-icons>
          <text class="section-title">最近更新</text>
        </view>
        <view class="header-right" @click="handleMoreUpdates">
          <text class="more-text">更多</text>
          <uni-icons type="arrow-right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <view class="update-item" v-for="(item, index) in updates" :key="index" >
        <image :src="item.iconClass" mode="aspectFill"></image>
        <view class="content" @click="navigateToDetails(item.id)">
          <view class="content-top">
            <text class="title">{{ item.title }}</text>
            <view class="free-tag" >免费</view>
          </view>
          <text class="date">{{ item.createTime }}</text>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <uni-tabbar :current="currentTab" :tabs="tabBarItems" @change="handleChangeTab"></uni-tabbar>
  </view>
</template>

<script>
import { getCategoryList } from '@/api/category.js';
import { getProject,getNoticeText } from '@/api/index.js';
import { getBanner } from '@/api/banner.js';
export default {
  // 1. 配置页面启用下拉刷新
  onPullDownRefresh() {
    console.log('开始下拉刷新');
    // 调用刷新数据的方法
    this.refreshData();
  },
  
  data() {
    return {
		searchValue: '', // 定义一个变量绑定输入值
      current: 0,
      animationData: {},
      bannerData: [
        { src: require('@/static/images/banner/banner01.jpg') },
        { src: require('@/static/images/banner/banner02.jpg') },
        { src: require('@/static/images/banner/banner03.jpg') }
      ],
      currentTab: 0,
	  //分类模块
      modules: [],
	  //最近更新
      updates: [],
      tabBarItems: [
        { pagePath: '/pages/home/home', text: '首页' },
        { pagePath: '/pages/category/category', text: '分类' },
        { pagePath: '/pages/card/card', text: '卡密激活' },
        { pagePath: '/pages/profile/profile', text: '我的' }
      ],
      noticeText: '欢迎来到抖工队学堂！最新课程已上线，限时优惠不容错过。点击查看更多精彩内容！这里是一段很长的通知文本，用来测试自动滚动功能是否正常工作。'
    };
  },
  mounted() {
    this.startMarquee();
	this.loadCategories();
	this.getProject();
	this.loadBanner();
	this.getNoticeText();
  },
  
   
  methods: {
    // 广告加载成功回调
    onAdLoad(e) {
      console.log('广告加载成功', e)
    },
    
    // 广告加载失败回调
    onAdError(e) {
      console.log('广告加载失败', e)
      // 可以在这里添加广告加载失败的处理逻辑
    },
    
    // 2. 新增刷新数据的方法
    async refreshData() {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '刷新中...'
        });
        
        // 重新加载所有数据
        await Promise.all([
          this.loadBanner(),
          this.loadCategories(),
          this.getProject()
        ]);
        
        // 刷新成功提示
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });
      } catch (error) {
        console.error('刷新失败:', error);
        uni.showToast({
          title: '刷新失败',
          icon: 'none',
          duration: 1500
        });
      } finally {
        // 3. 无论成功失败，都停止下拉刷新动画
        uni.stopPullDownRefresh();
        // 隐藏加载提示
        uni.hideLoading();
      }
    },
	async getNoticeText(){
	  try{
		  const res=  await getNoticeText();
		  if(res.code ===200 && res.data){
			this.noticeText = res.data;
		  }else{
			this.$modal.showToast('获取公告失败');
			this.bannerData = '';
		  }
			  
		}catch (error) {
		  console.error('获取公告失败:', error);
		  this.$modal.showToast('网络错误，获取公告失败');
		  this.bannerData = '';
		}
			    
	},
		  
	  async loadBanner() {
	    try {
	      // 调用后端API获取二维码
	      const response = await getBanner();
	      
	      // 假设后端返回格式为 { code: 200, data: { url: '二维码图片URL' } }
	      if (response.code === 200 && response.data) {
	        this.bannerData = response.data;
			console.log(this.bannerData)
	      } else {
	        this.$modal.showToast('获取轮播图失败');
	        this.bannerData = '';
	      }
	    } catch (error) {
	      console.error('获取轮播图失败:', error);
	      this.$modal.showToast('网络错误，获取轮播图失败');
	      this.bannerData = '';
	    }
	  },
	  
	  async getProject() {
	     try {
	       const res = await getProject();
	       if (res.code === 200) { // 假设成功状态码为 200
	         this.updates = res.data.records;
	       } else {
	         uni.showToast({
	           title: '数据加载失败',
	           icon: 'none'
	         });
	       }
	     } catch (error) {
	       console.error('获取列表失败:', error);
	       uni.showToast({
	         title: '请求异常',
	         icon: 'none'
	       });
	     }
	  },
	  
	//得到全部分类
	  async loadCategories() {
	     try {
	       const res = await getCategoryList();
	       if (res.code === 200) { // 假设成功状态码为 200
	         this.modules = res.data;
	       } else {
	         uni.showToast({
	           title: '分类数据加载失败',
	           icon: 'none'
	         });
	       }
	     } catch (error) {
	       console.error('获取分类列表失败:', error);
	       uni.showToast({
	         title: '请求异常',
	         icon: 'none'
	       });
	     }
	  },
	  
	  handleSearch() {
	         // 去除首尾空格
	         const keyword = this.searchValue.trim();
	         
	         if (keyword) {
	           // 有搜索内容时跳转
	           uni.navigateTo({
	             url: `/pages/AllResources/AllResources?title=${encodeURIComponent(keyword)}`
	           });
			   
				// 搜索成功后清空输入框
			 this.searchValue = '';
	         } else {
	           // 无内容时提示
	           uni.showToast({
	             title: '请输入搜索内容',
	             icon: 'none',
	             duration: 2000
	           });
	         }
	       },
	       
    navigateToAllCategories() {
	   uni.switchTab({
		 url: `/pages/work/index`
	   })
	 },

    navigateToModule(module) {
      console.log('跳转到模块:', module.id);
	  uni.navigateTo({
	    url: `/pages/AllResources/AllResources?categoryId=${module.id}`
	  })
    },
    
	navigateToDetails(projectId){
		console.log(projectId)
		uni.navigateTo({
		  url: `/pages/project/project?projectId=${projectId}`
		})
	},
	
    handleChangeTab(e) {
      this.currentTab = e.index;
    },
    
    changeSwiper(e) {
      this.current = e.detail.current;
    },
    
    clickBannerItem(item) {
      console.log('点击了轮播图项:', item);
    },
    
    handleMoreUpdates() {
      console.log('点击了更多更新');
      uni.navigateTo({ url: '/pages/AllResources/AllResources' });
    },
    
    startMarquee() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.notice-content').boundingClientRect();
      query.select('.notice-text').boundingClientRect().exec((res) => {
        const contentWidth = res[0].width;
        const textWidth = res[1].width;

        if (textWidth > contentWidth) {
          const duration = textWidth / 40; // 调整速度
          const animation = uni.createAnimation({
            duration: duration * 1000,
            timingFunction: 'linear'
          });

          const animate = () => {
            animation.translateX(-textWidth).step();
            this.animationData = animation.export();
            
            // 动画结束后重置并重新开始
            setTimeout(() => {
              animation.translateX(contentWidth).step({ duration: 0 });
              this.animationData = animation.export();
              setTimeout(animate, 20); // 短暂延迟后重新开始
            }, duration * 1000);
          };
          
          // 初始位置在右侧
          animation.translateX(contentWidth).step({ duration: 0 });
          this.animationData = animation.export();
          setTimeout(animate, 20);
        }
      });
    }
  }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.container {
  padding: 20rpx;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20rpx;
}

.swiper {
  height: 300rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.swiper-item {
  width: 100%;
  height: 100%;
}

.swiper-item image {
  width: 100%;
  height: 100%;
}

/* 新增广告位样式 */
.ad-container {
  margin-bottom: 20rpx;
  width: 100%;
  display: flex;
  justify-content: center;
}

.banner-ad {
  width: 100%;
  height: 150rpx; /* 标准Banner广告高度 */
}

/* 滚动通知栏样式 */
.notice-bar-container {
  display: flex;
  align-items: center;
  background-color: #fff9f9;
  border: 1px solid #ffd6d6;
  border-radius: 10rpx;
  padding: 15rpx 20rpx;
  margin-bottom: 20rpx;
}

.notice-icon {
  margin-right: 15rpx;
  flex-shrink: 0;
}

.notice-content {
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
}

.notice-text {
  font-size: 26rpx;
  color: #e60000;
  display: inline-block;
  /* animation: marquee 10s linear infinite; /* 备用CSS动画方案 */
}

/* 五行功能模块样式 */
.function-modules-container {
  margin-bottom: 30rpx;
}

.function-modules-card {
  background-color: #ffffff;
  border-radius: 15rpx;
  padding: 20rpx 10rpx;
  box-sizing: border-box;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-wrap: wrap;

}

.module-item {
  width: 20%;
  text-align: center;
  padding: 15rpx 5rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.module-icon-wrapper {
  width: 70rpx;
  height: 70rpx;
  background-color: #f0f8ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
  transition: transform 0.2s ease;
}

.module-item:active .module-icon-wrapper {
  transform: scale(0.95);
}

.module-icon {
  width: 40rpx;
  height: 40rpx;
}

.module-title {
  font-size: 22rpx;
  color: #333;
}

/* 最近更新模块样式 */
.recent-updates {
  margin-bottom: 20rpx;
}

.updates-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left .section-title {
  margin-bottom: 0;
  margin-left: 10rpx;
}

.header-right {
  display: flex;
  align-items: center;
  padding: 10rpx 15rpx;
  border-radius: 20rpx;
  transition: background-color 0.2s;
}

.header-right:active {
  background-color: #f5f5f5;
}

.more-text {
  font-size: 28rpx;
  color: #999;
  margin-right: 5rpx;
}

.update-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 15rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
}

.update-item image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 8rpx;
}

.update-item .content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.content-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.update-item .content .title {
  font-size: 28rpx;
  flex: 1;
  margin-right: 10rpx;
}

.free-tag {
  background-color: #1890ff;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 16rpx; /* 增加左右内边距 */
  border-radius: 6rpx;
  flex-shrink: 0;
  white-space: nowrap; /* 防止文字换行 */
}

.update-item .content .date {
  color: #888;
  font-size: 24rpx;
}

.search-container {
  padding: 10px 16px;
  background-color: #f5f5f5;
}

.search-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 20px;
  padding: 8px 16px;
}

.search-input {
  flex: 1;
  height: 16px;
  font-size: 10px;
  padding-right: 30px; /* 给图标留出空间 */
  border: none;
  outline: none;
}

.search-input::placeholder {
  color: #999999;
}

.search-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #999999;
  cursor: pointer;
  padding: 4px;
}

/* 点击图标时的反馈效果 */
.search-icon:active {
  opacity: 0.7;
}


/* 备用CSS动画方案
@keyframes marquee {
  0%   { transform: translateX(100%); }
  100% { transform: translateX(-100%); }
}
*/
</style>
